<template>
    <div>
      <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加购物车项按钮  批量删除   -->
      <el-row>
        <el-col :span="2"></el-col>
        <el-col :span="3">
             <el-input placeholder="请输入餐品名称搜索" v-model="query.foodName"/>
        </el-col>
        <el-col :span="4">
          <el-select v-model="query.businessId" placeholder="选择商家" >
              <el-option :value="null" label="请选择商家"/>
              <el-option
                  v-for="business in allBusinessList"
                  :key="business.businessId"
                  :label="business.businessName"
                  :value="business.businessId"
              />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="query.userId" placeholder="选择用户" >
              <el-option :value="null" label="请选择用户"/>
              <el-option
                  v-for="user in allUserList"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
              />
          </el-select>
        </el-col>
        <el-col :span="2">
                <el-button type="primary" plain @click="getByPage">搜索</el-button>
        </el-col>
        <el-col :span="3">
                <el-button type="success" plain @click="showDialog">新增购物车项</el-button>
        </el-col>
        <el-col :span="3">
                <el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
        </el-col>
        
      </el-row>
      <!-- 表格 -->
      <el-row>
        <el-col :span="2"></el-col>
        <el-col :span="20">
            
          <el-table :data="pb.data" 
                    stripe 
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection"  width="55" />
            <el-table-column type="index" width="50" />
            <el-table-column prop="business.businessName" label="购物车项名称" width="120px"/>
            <el-table-column prop="food.foodName" label="餐品名称" width="120px" show-overflow-tooltip/>
            <el-table-column prop="user.userName" label="用户名" width="120px" show-overflow-tooltip/>
            <el-table-column label="主图">
                <template #default="scope">
                    <el-image style="width: 50px" :src="scope.row.food.foodImg" fit="contain" />
                </template>
            </el-table-column>
            <el-table-column label="价格" width="70px">
                <template #default="scope">
                    ￥{{scope.row.food.foodPrice}}
                </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="70px"/>
            <el-table-column label="金额小计" width="120px">
                <template #default="scope">
                      ￥{{scope.row.food.foodPrice*scope.row.quantity}}
                </template>
              </el-table-column>
            <el-table-column label="操作" width="200px">
                  <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row.cartId)">
                      编辑
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.row.cartId)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
          </el-table>
            
        </el-col>
        
      </el-row>  
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="6"></el-col>
        <el-col :span="12">
             <el-pagination
                  v-model:current-page="query.pageNow"
                  v-model:page-size="query.pageCount"
                  :page-sizes="[5, 8, 10, 20]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pb.totalRows"
                  @size-change="getByPage"
                  @current-change="getByPage"
                />
        </el-col>
        
      </el-row>  
      
      <!-- 编辑购物车项信息的对话框  用于添加和修改 -->
      <el-dialog v-model="dialogFormVisible" title="编辑购物车项信息" width="500" draggable>
          <el-form :model="form">
            <el-form-item label="商家" :label-width="formLabelWidth">
              <el-select 
                  v-model="form.businessId" 
                  placeholder="选择商家" 
                  @change="getFoodByBId">
                  <el-option
                      v-for="business in allBusinessList"
                      :key="business.businessId"
                      :label="business.businessName"
                      :value="business.businessId"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="用户" :label-width="formLabelWidth">
              <el-select v-model="form.userId" placeholder="选择用户" >
                  <el-option
                      v-for="user in allUserList"
                      :key="user.userId"
                      :label="user.userName"
                      :value="user.userId"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="餐品" :label-width="formLabelWidth">
              <el-select v-model="form.foodId" placeholder="选择餐品" >
                  <el-option
                      v-for="food in foodList"
                      :key="food.foodId"
                      :label="food.foodName"
                      :value="food.foodId"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth">
                  <el-input-number v-model="form.quantity" :min="1"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="addOrUpdate">
                确认提交
              </el-button>
            </div>
          </template>
    </el-dialog>
      
    </div>
  </template>
  
  <script setup>
  import { onMounted, ref, getCurrentInstance } from 'vue';
  import { ElMessage,ElMessageBox } from 'element-plus';
  import { nanoid } from 'nanoid';
  
    let {proxy} = getCurrentInstance();
  
    //对话框是否显示
    let dialogFormVisible = ref(false);
    let formLabelWidth = ref('100px');
    
    //表单数据 添加和修改
    let form = ref({
        businessId: null,
        userId: null,
        foodId: null,
        quantity: 1
    })
    
    //生成购物车项账号的函数
    const generateAccount = ()=>{
        let account = nanoid().replaceAll("_","").replaceAll("-","");
        console.log(account);
        let startIndex = Math.floor(Math.random()*10);
        account = account.substring(startIndex,startIndex+9);
        console.log(account);
        return account;
    }
    
    //点新增购物车项信息按钮弹出对话框
    const showDialog = ()=>{
        
        dialogFormVisible.value = true;
        //数据清除
        form.value = {
          businessId: null,
          userId: null,
          foodId: null,
          quantity: 1
        };
        
    }
  
    //分页+搜索条件
    let query = ref({
        pageNow: 1,
        pageCount: 5,
        foodName: '',
        businessId: null,
        userId: null
    })
    
    //分页对象 totalRows  totalPages  data(集合)
    let pb = ref({
        totalRows: 0,
        totalPages: 0,
        data: []
    })
  
    const getByPage = ()=>{
        proxy.$axios({
            method: 'post',
            url: '/cart/page',
            data: query.value
        }).then(res=>{
            console.log(res);
            let resultBean = res.data;
            if(resultBean.code==200){
              let pageBean = resultBean.data; 
              pb.value = pageBean;// totalRows  totalPages  data(集合)
            }else{
                ElMessage.error(resultBean.msg);
            }
        })
    }
    
    //添加或修改
    const addOrUpdate = ()=>{
        proxy.$axios({
            method: 'post',
            url: '/cart',
            data: form.value
        }).then(res=>{
            let resultBean = res.data;
            if(resultBean.code == 200){
                getByPage();
                dialogFormVisible.value = false;
                ElMessage.success('保存购物车项信息成功');
            }else{
                ElMessage.error(resultBean.msg);
            }
        })
    }
    
    //处理数据回显
    const handleEdit = (cartId)=>{
        console.log('回显：cartId----',cartId);
        //根据id查询对应的实体数据
        proxy.$axios({
            method: 'get',
            url: '/cart/'+cartId
        }).then(res=>{
            let resultBean = res.data;
            if(resultBean.code == 200){
                form.value = resultBean.data;
                dialogFormVisible.value = true;
            }else{
                ElMessage.error(resultBean.msg);
            }
        })
    }
    
    //处理删除
    const handleDelete = (cartId)=>{
        console.log('删除：cartId----',cartId);
        ElMessageBox.confirm(
            '您确定要删除该购物车项信息吗？',
            '删除提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
                
                //确定删除
                proxy.$axios({
                    method: 'delete',
                    url: '/cart/'+cartId
                }).then(res=>{
                    let resultBean = res.data;
                    if(resultBean.code == 200){
                        ElMessage.success('删除成功');
                        getByPage();
                    }else{
                        ElMessage.error(resultBean.msg);
                    }
                })
                
            })
            .catch(() => {
                 ElMessage.info('取消删除');
            })
    }
    
    // const selectable = (row,index)=>{
       //  console.log('selectable',row,index);
       //  return true;
    // }
    
    //选中项的id集合
    let selectOptions = ref([]);
    
    //表格中多选框选中或取消时会触发  也就是选中项变化
    const handleSelectionChange = (newSelection)=>{
        console.log('选中项改变',newSelection);
        selectOptions.value = []; //清空
        newSelection.forEach((selOp)=>{
            console.log(selOp.cartId);
            selectOptions.value.push(selOp.cartId);
        });
    }
    
    //批量删除的函数
    const handleBatchDel = ()=>{
        console.log(selectOptions.value);
        if(selectOptions.value.length==0){
            ElMessage.info('请选中至少一条记录之后再进行删除');  
            return;
        }
        
        ElMessageBox.confirm(
            '您确定要删除选中的购物车项信息吗？',
            '删除提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
  
              console.log(selectOptions.value);
              console.log(typeof(selectOptions.value));
              console.log(JSON.stringify(selectOptions.value));
  
              let str = JSON.stringify(selectOptions.value);
              str = str.substring(1,str.length-1);
                      
                      //确定删除
                  proxy.$axios({
                      method: 'post',
                      url: '/cart/batch/'+str,
                  }).then(res=>{
                      let resultBean = res.data;
                      if(resultBean.code == 200){
                          ElMessage.success('删除成功');  
                          getByPage();
                      }else{
                          ElMessage.error(resultBean.msg);
                      }
                  })
                    
                      
            })
            .catch(() => {
                 ElMessage.info('取消删除');
            })
    }
  
    //---------存放所有用户-----------------------
    const allUserList = ref([])
  
    //---------查询所有用户-------------------
    const getAllUser = ()=>{
      proxy.$axios({
          method: 'get',
          url: '/user/all'
      }).then(res=>{
          let resultBean = res.data;
          if(resultBean.code == 200){
              allUserList.value = resultBean.data;
          }
      })
    }
  
    //--------存放所有商家------------
    const allBusinessList = ref([]);
  
    //---------查询所有商家---------------
    const getAllBusiness = ()=>{
      proxy.$axios({
          method: 'get',
          url: '/business/all'
      }).then(res=>{
          let resultBean = res.data;
          if(resultBean.code == 200){
              allBusinessList.value = resultBean.data;
          }
      })
    }
  
  
    //--------存放所有商家------------
    const foodList = ref([]);
  
    //---------查询所有商家---------------
    const getFoodByBId = (bid)=>{
      console.log('*****************',bid);
      form.value.foodId = null;
      proxy.$axios({
          method: 'get',
          url: '/food/business/'+bid
      }).then(res=>{
          let resultBean = res.data;
          if(resultBean.code == 200){
              foodList.value = resultBean.data;
          }
      })
    }
    
    onMounted(()=>{
        getByPage();
        getAllBusiness();
        getAllUser();
    })
  
  
  </script>
  
  <style scoped>
      .avatar-uploader .avatar {
        width: 100px;
        height: 100px;
        display: block;
      }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }
  </style>